package com.sbtr.controller;

import com.sbtr.business.datainfo.service.ConnectInfoService;
import com.sbtr.common.PageDto;
import com.sbtr.common.Response;
import com.sbtr.open.datainfo.dto.ConnectInfoDto;
import com.sbtr.open.datainfo.dto.SQLRequestDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 数据库链接信息维护管理
 */
@RestController
@RequestMapping("/databaseinfo")
@Api(tags = "建模数据管理模块（包括数据库链接信息维护管理+SQL在线定义查询）")
public class DatabaseInfoController {

    @Autowired
    private ConnectInfoService connectInfoService;

    @RequestMapping(value = "/history", method = RequestMethod.GET)
    @ApiOperation(value = "获取创建人所有连接", notes = "获取创建人所有连接", httpMethod = "GET")
    public Response<List<ConnectInfoDto>> getConnectInfo(@RequestParam("creater") String creater) {
        List<ConnectInfoDto> connectInfoDto = connectInfoService.getConnectInfoDto(creater);
        return Response.success(connectInfoDto);
    }

    @RequestMapping(value = "/update-database", method = RequestMethod.GET)
    @ApiOperation(value = "更新连接账号密码", notes = "更新连接账号密码", httpMethod = "GET")
    public Response<String> updataDatabase(@RequestParam("id") Long id, @RequestParam("user") String user,
                                           @RequestParam("password") String password) {
        int code = connectInfoService.updataDatabase(id, user, password);
        if (code == 200) {
            return Response.success("数据更新成功", "数据更新成功");
        } else if (code == 1045) {
            return Response.error(code, "账号密码错误");
        } else if (code == 1044) {
            return Response.error(code, "账号无权限访问");
        } else {
            return Response.error(code, "其他错误，请联系管理员");
        }

    }

    @RequestMapping(value = "/delete-database", method = RequestMethod.POST)
    @ApiOperation(value = "删除连接", notes = "删除连接", httpMethod = "POST")
    public Response<Boolean> deleteDatabase(@RequestParam Long id) {
        return Response.success("删除成功", connectInfoService.deleteDatabase(id));

    }

    @RequestMapping(value = "/insert-database", method = RequestMethod.POST)
    @ApiOperation(value = "添加连接", notes = "添加连接", httpMethod = "POST")
    public Response<String> insertDatabase(@RequestBody ConnectInfoDto dto) {
        int code = connectInfoService.insertDatabase(dto);
        if (code == 200) {
            return Response.success("添加连接", "连接添加成功");
        } else if (code == 1049) {
            return Response.error(code, "数据库错误");
        } else if (code == 0) {
            return Response.error(code, "ip或端口错误");
        } else if (code == 1045) {
            return Response.error(code, "账号或密码错误");
        } else if (code == 1044) {
            return Response.error(code, "账号无权限访问");
        } else if (code == 300) {
            return Response.error(code, "连接名已存在，请换一个");
        } else {
            return Response.error(code, "其他错误，请联系管理员");
        }
    }

    /**
     * 对list集合进行分页处理
     *
     * @return
     */

    private PageDto<String> ListSplitToPage(List<String> list, int page, String likeStr, int pageSize) {
        PageDto<String> pageDto = new PageDto<>();
        List<String> likeList = new ArrayList<String>();
        if (StringUtils.isBlank(likeStr)) {
            likeList = list;
        } else {
            Pattern pattern = Pattern.compile(likeStr);
            for (int i = 0; i < list.size(); i++) {
                if (pattern.matcher(list.get(i)).find()) {
                    likeList.add(list.get(i));
                }
            }
        }

        int total = likeList.size();
        List<String> newList = likeList.subList(pageSize * (page - 1),
                ((pageSize * page) > total ? total : (pageSize * page)));
        pageDto.setPage(page);
        pageDto.setPageSize(pageSize);
        pageDto.setRowCount(total);
        pageDto.setList(newList);
        return pageDto;
    }

    @RequestMapping(value = "/get-table-list/{id}", method = RequestMethod.GET)
    @ApiOperation(value = "获取材料数据库下所有表", notes = "获取数据库下所有表", httpMethod = "GET")
    public Response<PageDto<String>> getTableList(@PathVariable("id") Long id,
                                                  @RequestParam(name = "page", defaultValue = "1") int page,
                                                  @RequestParam(name = "likeStr", required = false) String likeStr,
                                                  @RequestParam(name = "pageSize", defaultValue = "6") int pageSize) {
        // return Response.success(connectInfoService.getTableList(id));
        return Response.success(ListSplitToPage(connectInfoService.getTableList(id), page, likeStr, pageSize));
    }

    @RequestMapping(value = "/get-by-table", method = RequestMethod.GET)
    @ApiOperation(value = "查询表获取结果", notes = "查询表获取结果", httpMethod = "GET")
    public Response<List<Map<String, Object>>> getByTable(@RequestParam("id") Long id,
                                                          @RequestParam("tableName") String tableName) {
        return Response.success(connectInfoService.getByTable(id, tableName));
    }

    @RequestMapping(value = "/get-by-sql", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    @ApiOperation(value = "根据sql获取结果", notes = "根据sql获取结果", httpMethod = "POST", produces = "application/json;charset=utf-8")
    public Response<List<Map<String, Object>>> getBySql(@RequestBody SQLRequestDto requestDto) {
        Long id = requestDto.getId();
        String sql = requestDto.getSql();

        if (sql == null || id == null) {
            throw new RuntimeException("id或sql不能为空");
        }
        return Response.success(connectInfoService.getBySql(requestDto));
    }

    @RequestMapping(value = "/checkout-illegal", method = RequestMethod.POST)
    @ApiOperation(value = "检查sql是否合法", notes = "检查sql是否合法", httpMethod = "POST")
    public Response<Boolean> checkoutIllegal(@RequestParam("sql") String sql, @RequestParam("type") String type) {
        return Response.success(connectInfoService.checkoutIllegal(sql, type));
    }

}
